<?php
    $pre_install_errors = array();
    function pre_flight_check()
    {            
        global $pre_install_errors; 
        global $already_installed;   
        // check for sql file
        $install_file = SITE_BASE.'/db/install.sql';
        if (!file_exists($install_file))
        { 
            $pre_install_errors[] = 'install.sql file is missing. Install can not proceed without this file.';
        }
        // check that the cache dir is writable
        if ( !is_writable(CACHE) ) 
        {
            $pre_install_errors[] = 'The <b>cache</b> directory  [ /pixel/app ] is not writable by the server (try 777).';
        }
        // check on the files directory
        if ( !is_writable(PUBLIC_HTML.'/files') )
        {
            $pre_install_errors[] = 'The <b>files</b> directory  [ /public_html/files ] is not writable by the server (try 777).';
        }
        if(count($pre_install_errors) > 0) 
        {
            return false;
        }
        
        // db will die if it cant connect.
        $db = ActiveRecord::connect();
        if(!$db) 
        { 
            $pre_install_errors[] = 'Your database connection failed. Please make sure the values in config/database.php are correct for the production section.';
            return false;
        }
                                         
        // check if its already been installed
        $table_check = $db->GetCol('SHOW TABLES');
        if ( in_array(DB_PREFIX.'users',$table_check) )
        {
            $pre_install_errors[] = 'Looks like you already have pixel-app installed. 
                If you want to reinstall it, you will need to drop the pixel-app tables first.';
            $already_installed = true;
            return false;
        } 
        return true;
    }       
    
    function install_pixel_app()
    {
        $install_file = SITE_BASE.'/db/install.sql';
                
        // run install file
        parse_sql_file($install_file);
        
        // create a temp password        
        use_model('users');
        $users = new Users();
        #$users->load(1);
        $users->set('user_login','admin');
        $users->set('user_password',$_POST['user_password']);
        $users->set('user_password_confirm',$_POST['user_password']); // silly setup hack.
        $users->change_pass = true;
        $users->set('first_name',$_POST['first_name']);
        $users->set('last_name',$_POST['last_name']);
        $users->set('email',$_POST['email']);
        $users->save();
        if ( !$users->has_no_errors() )
        {
            $header_tag = "h2";
        	$id			= 'error';
        	$class		= 'div_form_error_list';    	    	
        	
    		$header = content_tag($header_tag,'Error!');
    		$body   = content_tag('p','Your form contained the following errors:');
    		foreach( $users->get_errors() as $key => $value )
    		{
    		    $key     = ucwords(str_replace("_"," ",$key));
    			$errors .= content_tag('li',"$key: ".implode("<br>",$value));
    		}
    		$error_list = content_tag('ul',$errors);
    		echo content_tag('div',$header.$body.$error_list,array('class'=>$class,'id'=>$id));
    		return;
        }
        
        return content_tag('h2','Install Successful!').
               content_tag('p','Now that pixel app is installed, you can '.
                             link_to('login to the admin section',array('controller'=>'login'),array('target'=>'_blank'))).
               content_tag('p', "<b>username:</b> admin<br><b>password:</b> ".htmlentities($_POST['user_password'])).
               content_tag('h4','Make sure you delete or rename this install.php file!',array('class'=>'form_error')).
               content_tag('p','Also don\'t forget to delete the index.html file');

    }
    
    
    // utility functions - found on php.net someplace
    function parse_sql_file($url, $ignoreerrors = false) 
    {
        $db = ActiveRecord::connect();
        $file_content = file($url);        
        $query = "";
        foreach($file_content as $sql_line) {
            $sql_line = str_replace("{DB_PREFIX}",DB_PREFIX,$sql_line);
            $tsl = trim($sql_line);
            if (($sql_line != "") && (substr($tsl, 0, 2) != "--") && (substr($tsl, 0, 1) != "#")) {
                $query .= $sql_line;
                if(preg_match("/;\s*$/", $sql_line)) {
                    $result = $db->Execute($query);
                    if (!$result && !$ignoreerrors) die($db->ErrorMsg());
                    $query = "";
                }
            }
        }
    }
?>